<template>
  <Head title="订单详情 - Orange Tech" />
  <AdminLayout title="订单详情" subtitle="查看和管理订单信息">
    <div class="space-y-6">
      <!-- 返回按钮 -->
      <div>
        <Link
          :href="route('admin.orders.index')"
          class="inline-flex items-center text-gray-600 hover:text-gray-900"
        >
          <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
          </svg>
          返回列表
        </Link>
      </div>

      <!-- 订单基本信息 -->
      <div class="bg-white rounded-2xl p-8 shadow-sm">
        <div class="flex items-center justify-between mb-6">
          <div>
            <h2 class="text-2xl font-medium text-gray-900 mb-2">订单号：{{ order.order_number }}</h2>
            <p class="text-gray-600">下单时间：{{ formatDateTime(order.created_at) }}</p>
          </div>
          <div class="text-right">
            <span
              class="inline-flex items-center px-4 py-2 rounded-full text-lg font-medium"
              :class="getStatusClass(order.status)"
            >
              {{ getStatusText(order.status) }}
            </span>
          </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 pt-6 border-t border-gray-200">
          <div>
            <p class="text-sm text-gray-500 mb-1">用户信息</p>
            <p class="text-gray-900 font-medium">{{ order.user?.name || '-' }}</p>
            <p class="text-gray-600 text-sm">{{ order.user?.email || '-' }}</p>
          </div>
          <div>
            <p class="text-sm text-gray-500 mb-1">支付方式</p>
            <p class="text-gray-900 font-medium">{{ getPaymentMethodText(order.payment_method) }}</p>
            <span
              class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium mt-1"
              :class="getPaymentStatusClass(order.payment_status)"
            >
              {{ getPaymentStatusText(order.payment_status) }}
            </span>
          </div>
          <div>
            <p class="text-sm text-gray-500 mb-1">订单金额</p>
            <p class="text-2xl font-medium text-gray-900">¥{{ order.total_amount.toLocaleString() }}</p>
          </div>
        </div>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 左侧 -->
        <div class="lg:col-span-2 space-y-6">
          <!-- 商品信息 -->
          <div class="bg-white rounded-2xl p-8 shadow-sm">
            <h3 class="text-xl font-medium text-gray-900 mb-6">商品列表</h3>
            <div class="space-y-4">
              <div
                v-for="item in order.items"
                :key="item.id"
                class="flex gap-4 pb-4 border-b border-gray-200 last:border-0 last:pb-0"
              >
                <img :src="item.product_image || '/images/placeholder.jpg'" :alt="item.product_name" class="w-24 h-24 object-cover rounded-lg" />
                <div class="flex-1">
                  <p class="font-medium text-gray-900 text-lg">{{ item.product_name }}</p>
                  <p v-if="item.product_specs && item.product_specs.length > 0" class="text-sm text-gray-500 mt-1">
                    {{ item.product_specs.map(s => `${s.name}: ${s.value}`).join(' · ') }}
                  </p>
                  <div class="flex items-center justify-between mt-3">
                    <span class="text-gray-600">¥{{ item.price.toLocaleString() }} × {{ item.quantity }}</span>
                    <span class="text-lg font-medium text-gray-900">¥{{ item.subtotal.toLocaleString() }}</span>
                  </div>
                </div>
              </div>
            </div>

            <div class="mt-6 pt-6 border-t border-gray-200 space-y-2">
              <div class="flex justify-between text-sm">
                <span class="text-gray-600">商品小计</span>
                <span class="text-gray-900">¥{{ order.subtotal_amount.toLocaleString() }}</span>
              </div>
              <div class="flex justify-between text-sm">
                <span class="text-gray-600">运费</span>
                <span class="text-gray-900">¥{{ order.shipping_fee.toLocaleString() }}</span>
              </div>
              <div v-if="order.discount_amount > 0" class="flex justify-between text-sm">
                <span class="text-gray-600">优惠</span>
                <span class="text-red-600">-¥{{ order.discount_amount.toLocaleString() }}</span>
              </div>
              <div v-if="order.user_coupon" class="flex justify-between text-sm">
                <span class="text-gray-600">优惠券 ({{ order.user_coupon.coupon.name }})</span>
                <span class="text-red-600">-¥{{ (order.user_coupon.discount_amount || 0).toLocaleString() }}</span>
              </div>
              <div class="flex justify-between pt-2 border-t border-gray-200">
                <span class="font-medium text-gray-900">订单总额</span>
                <span class="text-xl font-medium text-gray-900">¥{{ order.total_amount.toLocaleString() }}</span>
              </div>
            </div>
          </div>

          <!-- 支付记录 -->
          <div v-if="order.payments && order.payments.length > 0" class="bg-white rounded-2xl p-8 shadow-sm">
            <h3 class="text-xl font-medium text-gray-900 mb-6">支付记录</h3>
            <div class="space-y-4">
              <div
                v-for="payment in order.payments"
                :key="payment.id"
                class="border border-gray-200 rounded-lg p-4"
              >
                <div class="flex items-center justify-between mb-2">
                  <div class="flex items-center space-x-3">
                    <span class="text-sm font-medium text-gray-900">
                      {{ getPaymentMethodText(payment.payment_method) }}
                    </span>
                    <span
                      class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                      :class="getPaymentStatusClass(payment.status)"
                    >
                      {{ getPaymentStatusText(payment.status) }}
                    </span>
                  </div>
                  <div class="text-right">
                    <div class="text-lg font-medium text-gray-900">¥{{ payment.amount.toLocaleString() }}</div>
                    <div class="text-xs text-gray-500">{{ formatDateTime(payment.created_at) }}</div>
                  </div>
                </div>
                <div v-if="payment.transaction_id" class="text-sm text-gray-600">
                  交易号：{{ payment.transaction_id }}
                </div>
                <div v-if="payment.paid_at" class="text-sm text-gray-600">
                  支付时间：{{ formatDateTime(payment.paid_at) }}
                </div>
              </div>
            </div>
          </div>

          <!-- 物流信息 -->
          <div v-if="order.status === 'shipped' || order.status === 'delivered'" class="bg-white rounded-2xl p-8 shadow-sm">
            <h3 class="text-xl font-medium text-gray-900 mb-6">物流信息</h3>
            <div class="space-y-3">
              <div class="flex">
                <span class="text-gray-600 w-24">物流公司：</span>
                <span class="text-gray-900">{{ order.shipping_company || '-' }}</span>
              </div>
              <div class="flex">
                <span class="text-gray-600 w-24">物流单号：</span>
                <span class="text-gray-900 font-mono">{{ order.tracking_number || '-' }}</span>
              </div>
              <div v-if="order.shipped_at" class="flex">
                <span class="text-gray-600 w-24">发货时间：</span>
                <span class="text-gray-900">{{ formatDateTime(order.shipped_at) }}</span>
              </div>
              <div v-if="order.shipping_note" class="flex">
                <span class="text-gray-600 w-24">发货备注：</span>
                <span class="text-gray-900">{{ order.shipping_note }}</span>
              </div>
            </div>
          </div>

          <!-- 收货信息 -->
          <div class="bg-white rounded-2xl p-8 shadow-sm">
            <h3 class="text-xl font-medium text-gray-900 mb-6">收货信息</h3>
            <div class="space-y-3">
              <div class="flex">
                <span class="text-gray-600 w-24">收货人：</span>
                <span class="text-gray-900">{{ order.receiver_name }}</span>
              </div>
              <div class="flex">
                <span class="text-gray-600 w-24">联系电话：</span>
                <span class="text-gray-900">{{ order.receiver_phone }}</span>
              </div>
              <div class="flex">
                <span class="text-gray-600 w-24">收货地址：</span>
                <span class="text-gray-900">{{ order.receiver_address }}</span>
              </div>
            </div>
          </div>

          <!-- 订单备注 -->
          <div v-if="order.notes" class="bg-white rounded-2xl p-8 shadow-sm">
            <h3 class="text-xl font-medium text-gray-900 mb-6">订单备注</h3>
            <p class="text-gray-700">{{ order.notes }}</p>
          </div>
        </div>

        <!-- 右侧：操作面板 -->
        <div class="lg:col-span-1 space-y-6 sticky top-8">
          <!-- 当前状态卡片 -->
          <div class="bg-white rounded-2xl p-6 shadow-sm">
            <h3 class="text-lg font-medium text-gray-900 mb-4 flex items-center">
              <svg class="w-5 h-5 mr-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
              </svg>
              当前状态
            </h3>
            <div class="space-y-3">
              <div class="flex items-center space-x-3">
                <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium" :class="getStatusBadgeClass()">
                  {{ getStatusText(order.status) }}
                  <span v-if="order.extended_status" class="ml-1 text-xs">
                    ({{ getExtendedStatusText(order.extended_status) }})
                  </span>
                </span>
              </div>
              <div v-if="order.status_changed_at" class="text-xs text-gray-500">
                更新于 {{ formatDateTime(order.status_changed_at) }}
              </div>
            </div>
          </div>

          <!-- 订单操作卡片 -->
          <div class="bg-white rounded-2xl p-6 shadow-sm">
            <h3 class="text-lg font-medium text-gray-900 mb-4 flex items-center">
              <svg class="w-5 h-5 mr-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4" />
              </svg>
              订单操作
            </h3>
            
            <div class="space-y-3">
              <!-- 支付相关操作 -->
              <div v-if="order.payment_status === 'pending'" class="space-y-2">
                <button
                  @click="handleMarkAsPaid"
                  class="w-full px-6 py-3 bg-green-600 text-white rounded-xl hover:bg-green-700 transition-colors flex items-center justify-center"
                >
                  <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  标记为已支付
                </button>
              </div>

              <!-- 物流相关操作 -->
              <div v-if="order.status === 'processing' && order.payment_status === 'paid'" class="space-y-2">
                <button
                  @click="showShipDialog = true"
                  class="w-full px-6 py-3 bg-blue-600 text-white rounded-xl hover:bg-blue-700 transition-colors flex items-center justify-center"
                >
                  <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
                  </svg>
                  发货
                </button>
              </div>

              <div v-if="order.status === 'shipped'" class="space-y-2">
                <button
                  @click="showConfirmDeliveryDialog = true"
                  class="w-full px-6 py-3 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition-colors flex items-center justify-center"
                >
                  <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                  </svg>
                  确认收货
                </button>
              </div>

              <!-- 危险操作 -->
              <div v-if="['pending', 'processing'].includes(order.status)" class="space-y-2 pt-2 border-t border-gray-100">
                <button
                  @click="showCancelDialog = true"
                  class="w-full px-6 py-3 border border-red-300 text-red-600 rounded-xl hover:bg-red-50 transition-colors flex items-center justify-center"
                >
                  <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                  </svg>
                  取消订单
                </button>
              </div>
            </div>
          </div>

          <!-- 售后管理卡片 -->
          <div class="bg-white rounded-2xl p-6 shadow-sm">
            <h3 class="text-lg font-medium text-gray-900 mb-4 flex items-center">
              <svg class="w-5 h-5 mr-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
              售后管理
            </h3>
            
            <!-- 售后操作按钮 -->
            <div class="space-y-3">
              <!-- 只有存在售后申请时才显示查看按钮 -->
              <Link
                v-if="order.after_sales_requests?.length > 0"
                :href="route('admin.after-sales.index', { order_number: order.order_number })"
                class="w-full px-6 py-3 bg-orange-600 text-white rounded-xl hover:bg-orange-700 transition-colors flex items-center justify-center"
              >
                <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                </svg>
                查看售后申请
              </Link>
              
              <!-- 没有售后申请时显示提示 -->
              <div v-else class="text-center py-6 bg-gray-50 rounded-xl">
                <div class="text-gray-500 text-sm">
                  <svg class="w-12 h-12 mx-auto mb-3 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                  </svg>
                  <p class="text-gray-400">暂无售后申请</p>
                </div>
              </div>
            </div>

            <!-- 最近售后申请 -->
            <div v-if="order.after_sales_requests?.length > 0" class="mt-6">
              <h5 class="text-sm font-medium text-gray-700 mb-3 flex items-center">
                <svg class="w-4 h-4 mr-1 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                最近申请
              </h5>
              <div class="space-y-3">
                <div 
                  v-for="request in order.after_sales_requests.slice(0, 3)" 
                  :key="request.id"
                  class="flex items-center justify-between p-3 bg-gray-50 rounded-xl hover:bg-gray-100 transition-colors"
                >
                  <div class="flex-1">
                    <div class="text-sm font-medium text-gray-900 flex items-center">
                      <span class="text-gray-400 mr-1">#</span>{{ request.id }}
                      <span class="mx-2 text-gray-300">-</span>
                      <span class="text-orange-600">{{ getAfterSalesTypeText(request.type) }}</span>
                    </div>
                    <div class="text-xs text-gray-500 mt-1">{{ formatDateTime(request.created_at) }}</div>
                  </div>
                  <div class="flex items-center space-x-2">
                    <span 
                      class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium"
                      :class="getAfterSalesStatusClass(request.status)"
                    >
                      {{ getAfterSalesStatusText(request.status) }}
                    </span>
                    <Link
                      :href="route('admin.after-sales.show', request.id)"
                      class="text-blue-600 hover:text-blue-700 text-xs font-medium px-2 py-1 rounded hover:bg-blue-50 transition-colors"
                    >
                      查看详情
                    </Link>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 订单进度卡片 -->
          <div class="bg-white rounded-2xl p-6 shadow-sm">
            <h3 class="text-lg font-medium text-gray-900 mb-4 flex items-center">
              <svg class="w-5 h-5 mr-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
              </svg>
              订单进度
            </h3>
            <div class="space-y-3">
              <!-- 进度条 -->
              <div class="relative">
                <div class="flex items-center justify-between">
                  <div class="flex items-center space-x-2">
                    <div class="w-3 h-3 rounded-full" :class="getStepClass('pending')"></div>
                    <span class="text-xs text-gray-600">待支付</span>
                  </div>
                  <div class="flex items-center space-x-2">
                    <div class="w-3 h-3 rounded-full" :class="getStepClass('processing')"></div>
                    <span class="text-xs text-gray-600">待发货</span>
                  </div>
                  <div class="flex items-center space-x-2">
                    <div class="w-3 h-3 rounded-full" :class="getStepClass('shipped')"></div>
                    <span class="text-xs text-gray-600">已发货</span>
                  </div>
                  <div class="flex items-center space-x-2">
                    <div class="w-3 h-3 rounded-full" :class="getStepClass('delivered')"></div>
                    <span class="text-xs text-gray-600">已送达</span>
                  </div>
                </div>
                <!-- 连接线 -->
                <div class="absolute top-1.5 left-0 right-0 h-0.5 bg-gray-200 -z-10">
                  <div class="h-full bg-blue-600 transition-all duration-500" :style="{ width: getProgressWidth() }"></div>
                </div>
              </div>
              
              <!-- 当前状态显示 -->
              <div class="text-center">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium" :class="getStatusBadgeClass()">
                  {{ getStatusText(order.status) }}
                  <span v-if="order.extended_status" class="ml-1 text-xs">
                    ({{ getExtendedStatusText(order.extended_status) }})
                  </span>
                </span>
              </div>
            </div>
          </div>

          <!-- 订单时间线卡片 -->
          <div class="bg-white rounded-2xl p-6 shadow-sm">
            <h3 class="text-lg font-medium text-gray-900 mb-4 flex items-center">
              <svg class="w-5 h-5 mr-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              订单时间线
            </h3>
            <div class="space-y-2 text-sm">
              <div v-if="order.created_at" class="flex justify-between">
                <span class="text-gray-600">创建时间</span>
                <span class="text-gray-900">{{ formatDateTime(order.created_at) }}</span>
              </div>
              <div v-if="order.paid_at" class="flex justify-between">
                <span class="text-gray-600">支付时间</span>
                <span class="text-gray-900">{{ formatDateTime(order.paid_at) }}</span>
              </div>
              <div v-if="order.shipped_at" class="flex justify-between">
                <span class="text-gray-600">发货时间</span>
                <span class="text-gray-900">{{ formatDateTime(order.shipped_at) }}</span>
              </div>
              <div v-if="order.delivered_at" class="flex justify-between">
                <span class="text-gray-600">送达时间</span>
                <span class="text-gray-900">{{ formatDateTime(order.delivered_at) }}</span>
              </div>
              <div v-if="order.cancelled_at" class="flex justify-between">
                <span class="text-gray-600">取消时间</span>
                <span class="text-gray-900">{{ formatDateTime(order.cancelled_at) }}</span>
              </div>
            </div>
          </div>

          <!-- 取消原因卡片 -->
          <div v-if="order.cancel_reason" class="bg-white rounded-2xl p-6 shadow-sm">
            <h3 class="text-lg font-medium text-gray-900 mb-4 flex items-center">
              <svg class="w-5 h-5 mr-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
              </svg>
              取消原因
            </h3>
            <p class="text-sm text-gray-700">{{ order.cancel_reason }}</p>
          </div>

          <!-- 状态变更历史卡片 -->
          <div v-if="order.status_history && order.status_history.length > 0" class="bg-white rounded-2xl p-6 shadow-sm">
            <h3 class="text-lg font-medium text-gray-900 mb-4 flex items-center">
              <svg class="w-5 h-5 mr-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
              </svg>
              状态变更历史
            </h3>
            <div class="space-y-2">
              <div v-for="(history, index) in order.status_history.slice().reverse()" :key="index" 
                   class="flex items-start space-x-3 p-2 bg-gray-50 rounded-lg">
                <div class="flex-shrink-0">
                  <div class="w-1.5 h-1.5 bg-gray-900 rounded-full mt-2"></div>
                </div>
                <div class="flex-1 min-w-0">
                  <div class="flex items-center justify-between">
                    <p class="text-sm font-medium text-gray-900">{{ history.action }}</p>
                    <p class="text-xs text-gray-500">{{ formatDateTime(history.timestamp) }}</p>
                  </div>
                  <p class="text-sm text-gray-600 mt-1">
                    从 <span class="font-medium">{{ getStatusText(history.from_status) }}</span>
                    变更为 <span class="font-medium">{{ getStatusText(history.to_status) }}</span>
                  </p>
                  <p v-if="history.reason" class="text-xs text-gray-500 mt-1">{{ history.reason }}</p>
                  <p class="text-xs text-gray-400 mt-1">操作人：{{ history.operator }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 发货对话框 -->
    <TransitionRoot as="template" :show="showShipDialog">
      <Dialog as="div" class="relative z-50" @close="showShipDialog = false">
        <TransitionChild
          as="template"
          enter="ease-out duration-300"
          enter-from="opacity-0"
          enter-to="opacity-100"
          leave="ease-in duration-200"
          leave-from="opacity-100"
          leave-to="opacity-0"
        >
          <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" />
        </TransitionChild>

        <div class="fixed inset-0 z-10 overflow-y-auto">
          <div class="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
            <TransitionChild
              as="template"
              enter="ease-out duration-300"
              enter-from="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
              enter-to="opacity-100 translate-y-0 sm:scale-100"
              leave="ease-in duration-200"
              leave-from="opacity-100 translate-y-0 sm:scale-100"
              leave-to="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
            >
              <DialogPanel class="relative transform overflow-hidden rounded-lg bg-white px-4 pb-4 pt-5 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg sm:p-6">
                <div>
                  <div class="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-blue-100">
                    <svg class="h-6 w-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
                    </svg>
                  </div>
                  <div class="mt-3 text-center sm:mt-5">
                    <DialogTitle as="h3" class="text-base font-semibold leading-6 text-gray-900">
                      订单发货
                    </DialogTitle>
                    <div class="mt-2">
                      <p class="text-sm text-gray-500">
                        请填写物流信息，订单将标记为已发货状态
                      </p>
                    </div>
                  </div>
                </div>

                <form @submit.prevent="handleShip" class="mt-5 space-y-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">物流公司</label>
                    <select
                      v-model="shipForm.shipping_company"
                      class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      <option value="">请选择物流公司</option>
                      <option value="顺丰速运">顺丰速运</option>
                      <option value="圆通速递">圆通速递</option>
                      <option value="中通快递">中通快递</option>
                      <option value="申通快递">申通快递</option>
                      <option value="韵达速递">韵达速递</option>
                      <option value="京东物流">京东物流</option>
                      <option value="EMS">EMS</option>
                      <option value="德邦快递">德邦快递</option>
                      <option value="百世快递">百世快递</option>
                      <option value="其他">其他</option>
                    </select>
                  </div>

                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">物流单号</label>
                    <input
                      v-model="shipForm.tracking_number"
                      type="text"
                      placeholder="请输入物流单号"
                      class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>

                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">发货备注</label>
                    <textarea
                      v-model="shipForm.shipping_note"
                      rows="3"
                      placeholder="请输入发货备注（可选）"
                      class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    ></textarea>
                  </div>

                  <div class="mt-5 sm:mt-6 sm:grid sm:grid-flow-row-dense sm:grid-cols-2 sm:gap-3">
                    <button
                      type="submit"
                      :disabled="processing"
                      class="inline-flex w-full justify-center rounded-md bg-blue-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600 sm:col-start-2 disabled:opacity-50"
                    >
                      {{ processing ? '发货中...' : '确认发货' }}
                    </button>
                    <button
                      type="button"
                      @click="showShipDialog = false"
                      class="mt-3 inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:col-start-1 sm:mt-0"
                    >
                      取消
                    </button>
                  </div>
                </form>
              </DialogPanel>
            </TransitionChild>
          </div>
        </div>
      </Dialog>
    </TransitionRoot>


    <!-- 确认收货对话框 -->
    <ConfirmDialog
      :show="showConfirmDeliveryDialog"
      type="info"
      title="确认收货"
      message="确定要标记此订单为已送达吗？"
      confirm-text="确认收货"
      cancel-text="取消"
      @close="showConfirmDeliveryDialog = false"
      @confirm="handleConfirmDelivery"
    />

    <!-- 取消订单对话框 -->
    <ConfirmDialog
      :show="showCancelDialog"
      type="danger"
      title="确认取消订单"
      message="确定要取消此订单吗？取消后库存将自动恢复。"
      confirm-text="取消订单"
      cancel-text="返回"
      @close="showCancelDialog = false"
      @confirm="handleCancelOrder"
    />
  </AdminLayout>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Head, Link, router } from '@inertiajs/vue3'
import { Dialog, DialogPanel, DialogTitle, TransitionChild, TransitionRoot } from '@headlessui/vue'
import { ExclamationTriangleIcon, InformationCircleIcon } from '@heroicons/vue/24/outline'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import ConfirmDialog from '@/Components/ConfirmDialog.vue'
import { useNotification } from '@/composables/useNotification'

const props = defineProps({
  order: { type: Object, required: true }
})

const { showSuccess, showError } = useNotification()
const showCancelDialog = ref(false)
const showShipDialog = ref(false)
const showConfirmDeliveryDialog = ref(false)
const processing = ref(false)

// 发货表单
const shipForm = reactive({
  shipping_company: '',
  tracking_number: '',
  shipping_note: ''
})


// 标记为已支付
const handleMarkAsPaid = () => {
  router.post(route('admin.orders.mark-paid', props.order.order_number), {}, {
    onSuccess: () => {
      // 后端已经发送了 flash 消息，这里不需要重复显示
    },
    onError: () => {
      showError('操作失败', '请重试')
    }
  })
}

// 发货
const handleShip = () => {
  processing.value = true
  
  router.post(route('admin.orders.ship', props.order.order_number), shipForm, {
    onSuccess: () => {
      showShipDialog.value = false
      // 重置表单
      shipForm.shipping_company = ''
      shipForm.tracking_number = ''
      shipForm.shipping_note = ''
      processing.value = false
    },
    onError: (errors) => {
      processing.value = false
      showError('发货失败', errors.message || '请重试')
    }
  })
}

// 取消订单
const handleCancelOrder = () => {
  router.post(route('admin.orders.cancel', props.order.order_number), {
    reason: '管理员取消'
  }, {
    preserveState: false,
    onSuccess: () => {
      // 后端已经发送了 flash 消息，这里不需要重复显示
      showCancelDialog.value = false
      selectedStatus.value = 'cancelled'
    },
    onError: () => {
      showError('取消失败', '请重试')
    }
  })
}

// 确认收货
const handleConfirmDelivery = () => {
  router.patch(route('admin.orders.update-status', props.order.order_number), {
    status: 'delivered'
  }, {
    preserveState: false,
    onSuccess: () => {
      showConfirmDeliveryDialog.value = false
      // 后端已经发送了 flash 消息，这里不需要重复显示
    },
    onError: (errors) => {
      showError('操作失败', errors.message || '请重试')
    }
  })
}

// 检查是否有可用操作
const hasAvailableActions = computed(() => {
  return (
    (props.order.payment_status === 'pending') ||
    (props.order.status === 'processing' && props.order.payment_status === 'paid') ||
    (props.order.status === 'shipped') ||
    (['pending', 'processing'].includes(props.order.status))
  )
})

const getStatusText = (status) => {
  const map = {
    'pending': '待支付',
    'processing': '待发货',
    'shipped': '已发货',
    'delivered': '已送达',
    'cancelled': '已取消'
  }
  return map[status] || status
}

const getExtendedStatusText = (extendedStatus) => {
  const map = {
    'partially_shipped': '部分发货',
    'completed': '已完成',
    'refunded': '已退款',
    'returned': '已退货',
    'partially_refunded': '部分退款',
    'partially_returned': '部分退货'
  }
  return map[extendedStatus] || extendedStatus
}

// 获取步骤样式
const getStepClass = (step) => {
  const currentStep = getCurrentStep()
  const stepIndex = getStepIndex(step)
  const currentIndex = getStepIndex(currentStep)
  
  if (stepIndex < currentIndex) {
    return 'bg-blue-600' // 已完成
  } else if (stepIndex === currentIndex) {
    return 'bg-blue-600 ring-2 ring-blue-200' // 当前步骤
  } else {
    return 'bg-gray-300' // 未完成
  }
}

// 获取当前步骤
const getCurrentStep = () => {
  if (props.order.status === 'cancelled') return 'cancelled'
  if (props.order.status === 'delivered') return 'delivered'
  if (props.order.status === 'shipped') return 'shipped'
  if (props.order.status === 'processing') return 'processing'
  return 'pending'
}

// 获取步骤索引
const getStepIndex = (step) => {
  const steps = ['pending', 'processing', 'shipped', 'delivered']
  return steps.indexOf(step)
}

// 获取进度条宽度
const getProgressWidth = () => {
  const currentStep = getCurrentStep()
  const stepIndex = getStepIndex(currentStep)
  const totalSteps = 4
  
  if (currentStep === 'cancelled') return '0%'
  
  return `${(stepIndex / (totalSteps - 1)) * 100}%`
}

// 售后相关方法
const getAfterSalesCountByStatus = (status) => {
  if (!props.order.after_sales_requests) return 0
  return props.order.after_sales_requests.filter(request => request.status === status).length
}

const getAfterSalesTypeText = (type) => {
  const typeMap = {
    return: '退货',
    refund: '退款',
    exchange: '换货'
  }
  return typeMap[type] || type
}

const getAfterSalesStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    approved: '已批准',
    rejected: '已拒绝',
    processing: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const getAfterSalesStatusClass = (status) => {
  const classes = {
    pending: 'bg-orange-100 text-orange-800',
    approved: 'bg-blue-100 text-blue-800',
    rejected: 'bg-red-100 text-red-800',
    processing: 'bg-indigo-100 text-indigo-800',
    completed: 'bg-green-100 text-green-800',
    cancelled: 'bg-gray-100 text-gray-800'
  }
  return classes[status] || 'bg-gray-100 text-gray-800'
}

const canCreateAfterSales = computed(() => {
  return props.order.status === 'delivered' && props.order.payment_status === 'paid'
})

const createAfterSales = () => {
  // 这里可以跳转到创建售后申请的页面
  router.visit(route('admin.after-sales.create', { order_id: props.order.id }))
}

// 获取状态徽章样式
const getStatusBadgeClass = () => {
  const statusClasses = {
    'pending': 'bg-orange-100 text-orange-700 border border-orange-200',      // 橙色 - 待处理
    'processing': 'bg-blue-100 text-blue-700 border border-blue-200',         // 蓝色 - 处理中
    'shipped': 'bg-indigo-100 text-indigo-700 border border-indigo-200',      // 靛蓝 - 运输中
    'delivered': 'bg-green-100 text-green-700 border border-green-200',       // 绿色 - 已完成
    'cancelled': 'bg-red-100 text-red-700 border border-red-200'              // 红色 - 已取消
  }
  
  return statusClasses[props.order.status] || 'bg-gray-100 text-gray-700 border border-gray-200'
}

const getStatusClass = (status) => {
  const map = {
    'pending': 'bg-orange-100 text-orange-700',
    'processing': 'bg-blue-100 text-blue-700',
    'shipped': 'bg-indigo-100 text-indigo-700',
    'delivered': 'bg-green-100 text-green-700',
    'cancelled': 'bg-red-100 text-red-700'
  }
  return map[status] || 'bg-gray-100 text-gray-700'
}

const getPaymentMethodText = (method) => {
  const map = {
    'alipay': '支付宝',
    'wechat': '微信支付',
    'cod': '货到付款',
    'mock': '模拟支付'
  }
  return map[method] || method || '-'
}

const getCouponTypeText = (type) => {
  const map = {
    'fixed': '固定金额',
    'percent': '百分比折扣',
    'free_shipping': '免运费'
  }
  return map[type] || type || '-'
}

const getPaymentStatusText = (status) => {
  const map = {
    'pending': '待支付',
    'paid': '已支付',
    'failed': '支付失败',
    'refunded': '已退款'
  }
  return map[status] || status
}

const getPaymentStatusClass = (status) => {
  const map = {
    'pending': 'bg-yellow-100 text-yellow-700',
    'paid': 'bg-green-100 text-green-700',
    'failed': 'bg-red-100 text-red-700',
    'refunded': 'bg-gray-100 text-gray-700'
  }
  return map[status] || 'bg-gray-100 text-gray-700'
}

const formatDateTime = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

